#encoding:utf8 

import os, sys, urllib, threading, logging, string, re, shutil
import uuid

class DlMgr():

	MAX_DL = 4
	RETRY_TIME = 3
	DL_PATH = os.getcwd()
	FILE_TYPES = ["mobi", "epub"]

	def __init__(self, dllist, callback = None):
		
		self._dllist = dllist
		self._dlpath = self.DL_PATH
		self._dlnum  = 0
		self._allnum = len(self._dllist)

		self._callback = callback

	def _dl_hook(self, *args, **kwds):
		(pidx, psize, maxsize) = args
		perc = float(pidx*psize)/float(maxsize)
		if perc >= 1:
			self._dlnum += 1
			self._dl_next()

	def _dl_next():
		#chk list 
		if len(self._dllist) == 0:
			if hasattr(self._callback, "__call__"):
				 self._callback()
		else:
			self._execure_dl()

	def _execure_dl(self):
		try:
			bookinfo = self._dllist.pop()
		except:
			logging.info("Download list is empty!Wait finish--->")
			return 
		url    = bookinfo["downurl"]
		name   = bookinfo["name"]


		#only chinaese filename
		'''
		pattren = re.compile(u"[\u4e00-\u9fa5]+").findall(name.decode("utf8"))
		ret = ''
		for cstr in pattren:
			ret = ret + cstr

		if len(pattren)>0:
			aa = urllib.urlretrieve(url,ret  + "." + format, reporthook = self._dl_hook)
		else:
			urllib.urlretrieve(url, name.decode("utf8").strip() + "." + format, reporthook = self._dl_hook)
		'''
		#just name
		logging.info("Now downloading file ----->>>%s, progress is ---->>>%s/%s", name, str(self._dlnum), str(self._allnum))
		bookinfo["dltime"] = 0
		def retry_dl():
			fname = name.decode("utf8").strip() + "." + self.FILE_TYPES[0]
			fname2 = name.decode("utf8").strip() + "." + self.FILE_TYPES[1]
			if os.path.isfile(os.path.join(self._dlpath, fname)) or os.path.isfile(os.path.join(self._dlpath, fname2)):
				logging.info("File {name} exit! pass~".format(name=name))
				self._dlnum += 1
				self._execure_dl()
			else:
				try:
					tmpname = str(uuid.uuid1())
					tmpfileobj = os.path.join(self._dlpath, tmpname)
					(tarurl, msg) = urllib.urlretrieve(url, tmpfileobj, reporthook = self._dl_hook)
					
					tarname = string.replace(string.split(item[33:], "=")[1], '''"''', '')   
					
					os.rename(tmpfileobj, os.path.join(self._dlpath, tarname))
					print (tarname)
					print (tarname)
					print (tarname)
					print (tarname)
					print (tarname)
					print (tarname)
					print (tarname)
					shutil.move(tarname, self._dlpath)
				except:
					bookinfo["dltime"] += 1
					if bookinfo["dltime"] > 5:
						logging.warn("fail to down the book {name} from {url}".format(name=name, url=url))
						self._dlnum += 1
						self._execure_dl()
					else:
						retry_dl()
		retry_dl()

	def set_dlpath(self, path):
		if os.path.isdir(path):
			self._dlpath = path
		else:
			logging.error("Not a useable filepath--->>>{path}".format(path))


	def start(self):
		'''
		多线程需要分组进行 不然判断文件存在会出现问题
		todo优化

		'''
		for t in range(4):
			s = threading.Thread(target = self._execure_dl)
			s.start()
		# self._execure_dl()


